FROM hub.oepkgs.net/openeuler/openeuler:24.03-lts-sp1 AS builder

RUN sed -i \
        -e '/^meta/ s/^\(.*\)$/#\1/g' \
        -e 's/repo.openeuler.org/repo.huaweicloud.com\/openeuler/g' \
        -e '/\[debuginfo\]/,$d' \
    /etc/yum.repos.d/openEuler.repo && \
    yum install -y python3-pip shadow

RUN pip config --user set global.index https://mirrors.huaweicloud.com/repository/pypi && \
    pip config --user set global.index-url https://mirrors.huaweicloud.com/repository/pypi/simple && \
    pip config --user set global.trusted-host mirrors.huaweicloud.com && \
    pip install uv

WORKDIR /app

RUN groupadd -r -g 666 app && \
    useradd -r -g app -u 666 -d /app -s /bin/false app

ADD pyproject.toml ./
ADD uv.lock ./
ADD src ./src

RUN uv venv && \
    uv sync --frozen --no-dev --index-url https://mirrors.huaweicloud.com/repository/pypi/simple && \
    uv pip install -e . --no-deps

FROM hub.oepkgs.net/openeuler/openeuler:24.03-lts-sp1

COPY --from=builder /etc/group /etc/group
COPY --from=builder /etc/passwd /etc/passwd

WORKDIR /app

RUN chown -R app:app /app && \
    chmod 755 /app && \
    chmod -R go-w /app

COPY --from=builder --chown=app:app /app/.venv ./.venv
COPY --from=builder --chown=app:app /app/src ./src
COPY --from=builder --chown=app:app /app/pyproject.toml ./

ENV PATH="/app/.venv/bin:$PATH" \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONPATH="/app" \
    PYTHONFAULTHANDLER=1 \
    KAFKA_MCP_BIND_HOST=0.0.0.0 \
    KAFKA_MCP_BIND_PORT=8003

USER app

EXPOSE 8003

HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD if [ "$KAFKA_MCP_SERVER_TRANSPORT" = "http" ] || [ "$KAFKA_MCP_SERVER_TRANSPORT" = "sse" ]; then \
            curl -I http://localhost:${KAFKA_MCP_BIND_PORT}/ >/dev/null 2>&1 || exit 1; \
        else \
            pgrep -f kafka-mcp-server >/dev/null 2>&1 || exit 1; \
        fi

CMD ["/app/.venv/bin/kafka-mcp-server"]
